package com.lzs.bootsafety.business.moni.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.lzs.bootsafety.business.moni.entity.SysOnlineUser;
import com.lzs.bootsafety.business.moni.service.SysOnlineUserService;
import com.lzs.bootsafety.common.base.controller.BaseController;
import com.lzs.bootsafety.common.config.shiro.session.MySessionDAO;
import com.lzs.bootsafety.common.config.shiro.session.OnlineSession;
import com.lzs.bootsafety.common.util.Resu;
import com.lzs.bootsafety.common.util.enums.OnlineStatus;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author LiuZhanShi
 * @Date 2020/7/31
 * @Version 1.0
 * @Desc 在线用户控制层
 */
@RequestMapping("/sys/online")
@RestController
public class OnlineUserController extends BaseController {
    @Autowired
    private SysOnlineUserService sysOnlineUserService;
    @Autowired
    private MySessionDAO mySessionDAO;
    /**在线用户*/
    @GetMapping("/list")
    public Resu list(String data){
        SysOnlineUser sysOnlineUser = JSON.parseObject(data,SysOnlineUser.class);
        PageInfo<SysOnlineUser> pageInfo = sysOnlineUserService.selectUserOnlineList(sysOnlineUser);
        return Resu.page(pageInfo.getList(),pageInfo.getTotal(),200);
    }
    /**强制退出在线用户*/
    @PostMapping("/forceLogout")
    public Resu forceLogout(String sessionId) {
        System.out.println("sessionID      :"+sessionId);
        SysOnlineUser online = sysOnlineUserService.selectOnlineById(sessionId);
        if (online == null) {
            return Resu.error("用户已离线");
        }
        OnlineSession onlineSession = (OnlineSession) mySessionDAO.readSession(online.getSessionId());
        if (onlineSession == null) {
            return Resu.error("用户已离线");
        }
        if (sessionId.equals(getSession().getId())) {
            return Resu.error("无法强退当前登录用户");
        }
        onlineSession.setStatus(OnlineStatus.off_line);
        mySessionDAO.update(onlineSession);
        online.setStatus(OnlineStatus.off_line);
        sysOnlineUserService.saveOnline(online);
        return Resu.error("强退成功");
    }
}
